//
//  ActivatePageLogic.swift
//  首页功能逻辑
//
//  Created by Season02 on 9/23/16.
//  Copyright © 2016 Season02. All rights reserved.
//
import Foundation
import React
import Locksmith
import SwiftHTTP
import HandyJSON

var _homeModule : homeModule? = nil

@objc(JsAndroid)//WTF
open class homeModule: RCTEventEmitter,IapDelegate
{
//    var bridge: RCTBridge!  // this is synthesized
    let iap = IapHelper()
    
    override init()
    {
        super.init()
        _homeModule = self
        
        iap.delegate = _homeModule
    }
    
    //获取手机型号 庶民iphone 高贵x 乡巴佬ipad
//    @objc(checkDevice:)
//    func checkDevice(_ device:(NSObject) -> ()) -> Void
//    {
//        device([Settings.checkDevice()] as NSObject)
//    }
    
    //获取域名根路径
    @objc(jsGetServerUrl:success:)
    func jsGetServerUrl(_ failed:(NSObject) -> (), success:(NSObject) -> ()) -> Void
    {
        let url = SRef.Const(const: .serverUrl)
        
        success([url] as NSObject)
    }
    
    //获取版本信息
    @objc(jsGetVersionName:success:)
    func jsGetVersionName(_ failed:(NSObject) -> (), success:(NSObject) -> ()) -> Void
    {
        success([Settings.currentVersion()] as NSObject)
    }
    
    //检查新版本
    @objc(jsVersion:success:)
    func jsVersion(_ failed:(NSObject) -> (), success:@escaping (NSObject) -> ()) -> Void
    {
        Settings.checkUpdateForAppID(ID: SRef.Const(const: .store_id)) { (status, current, new) in
            success([status,new] as NSObject)
        }
    }
    
    //清除缓存
    @objc(jsClearCache:success:)
    func jsClearCache(_ failed:(NSObject) -> (), success:(NSObject) -> ()) -> Void
    {
        let size = "本地数据"
        
        success([true,size] as NSObject)
    }
    
    //发起iap
    @objc func riseIap(_ price:Int) -> Void
    {
        iap.purchase(price: price)
    }
    
    //查询相册，相机权限
    @objc(camAuthStatus:)
    func camAuthStatus(_ result:(NSObject) -> ()) -> Void
    {
        let status = Settings.checkCamAlbAuth()
        
        let data = [["camera":status.0, "album":status.1]]
        
        result(data as NSObject)
    }
     
    //检查和发起相机权限检查
    @objc(checkAlbAuth:)
    func checkAlbAuth(_ result:@escaping (NSObject) -> ()) -> Void
    {
        Settings.checkAlbAuth { (status) in
            if status{
                let data = true
                result([data] as NSObject)
            }else{
                let data = false
                result([data] as NSObject)
            }
        }
    }
    
    //请求用户获取相册（相机）权限
    @objc(requestCamAuth)
    func requestCamAuth() -> Void
    {
        let url = URL(string:UIApplicationOpenSettingsURLString)
        
        if(UIApplication.shared.canOpenURL(url!)){
            UIApplication.shared.openURL(url!)
        }
    }
    
    //调用链接
    @objc(openUrl:)
    func openUrl(_ url:String) -> Void
    {
        DispatchQueue.global().async {
            DispatchQueue.main.async
                {
                    let Url = URL.init(string: url)
                    UIApplication.shared.openURL(Url!)
            }
        }
    }
    
    //唤起AppStore
    @objc(jsVersionqqdownloader:success:)
    func jsVersionqqdownloader(_ failed:(NSObject) -> (), success:(NSObject) -> ()) -> Void
    {
        Settings.riseAppStore(id:SRef.Const(const: .store_id))
        success([true] as NSObject)
    }
    
    //第三方登录 weixin(微信) qq(QQ) weibo(微博)
    @objc(jsOpenThirdPartyLoginActivity:)//zz名字
    func riseThirdpartLogin(_ type:String)
    {
        _homeModule = self
        
        switch type {
        case "weixin":
            TPWechat.riseLogin()
        case "qq":
            TPQQ.login()
        case "weibo":
            TPWeibo.login()
            
        default:
            return
        }
    }
    
    //用户登出
    @objc(jsUserExit:success:)//zz名字
    func logout(_ failed:(NSObject) -> (), success:(NSObject) -> ())
    {
        do{
            UserDefaults.standard.removeObject(forKey: Key_User_Token)
            UserDefaults.standard.removeObject(forKey: Key_User_Coin)
            
            try Locksmith.deleteDataForUserAccount(userAccount: Key_User_Account)
            try Locksmith.saveData(data: [Key_User_State: Value_User_State_Offline], forUserAccount: Key_User_Account)
        }
        catch let error
        {
            print("清除用户信息时出错: \(error)")
        }
        success([true] as NSObject)
    }
    
    //react 发起获取用户信息
    @objc//(jsGetLoginUserInfo:reject:)
    func jsGetLoginUserInfo(_ resolve: @escaping RCTPromiseResolveBlock,
                            rejecter reject: @escaping RCTPromiseRejectBlock){
        let dic = Locksmith.loadDataForUserAccount(userAccount: Key_User_Account)!
        let name = dic[Key_User_Name] as! String
        let id = dic[Key_User_Id] as! String
        let head = dic[Key_User_Head_Path] as! String
        
        let coin = UserDefaults.standard.integer(forKey: Key_User_Coin) //(forKey: Key_User_Coin) as! Int
        let token = UserDefaults.standard.object(forKey: Key_User_Token) as! String
        
        let data = ["id":id, "userName":name, "loginName":name, "userToken":token, "picMinPath":head, "picNormalPath":head, "coinIos":coin] as NSObject
        
        resolve(data)
    }
    
//    func checkDevice(_ device:(NSObject) -> ()) -> Void
//    {
//        device([Settings.checkDevice()] as NSObject)
//    }
    
    @objc//(jsGetLoginUserInfo:reject:)
    func checkDevice(_ resolve: @escaping RCTPromiseResolveBlock,
                            rejecter reject: @escaping RCTPromiseRejectBlock){
        resolve(Settings.checkDevice() as NSObject)
    }
    
    @objc(checkThirdStatus:)
    func checkThirdStatus(_ value:(NSObject) -> ())
    {
        let status = Status.login_status()
        
        let data = [["wechat":status.0, "qq":status.1, "weibo":false]] as NSObject
        
        value(data)
    }
    
    //imgPath 分享图片路径（name+".jpg"）,统一存储在Pictures文件夹下(what?)
    //type 分享类型：circle(朋友圈)，weixin(微信好友)，qq(QQ好友)，qzone(QQ空间)，weibo(微博)，more(更多)
//    jsOpenShareActivity:(NSString*)imgPath type:(NSString*)type failed:(RCTResponseSenderBlock)failed  success:(RCTResponseSenderBlock)success
//    @objc(jsOpenShareActivity:type:error:success:)
    @objc func jsOpenShareActivity(_ imgPath:String, type:String, failed:(NSObject) -> (), success:(NSObject) -> ())
    {
        switch type {
        case "weixin":
            TPWechat.shareToFriend(title: "影响", url: imgPath)
            
        case "circle":
            TPWechat.shareToTimeLine(title: "影响", url: imgPath)
            
        case "qq":
            TPQQ.shareTo(friend:true,title: "影响", img: imgPath)
            
        case "qzone":
            TPQQ.shareTo(friend:false,title: "影响", img: imgPath)
            
        default:
            return
        }
        
        success([true] as NSObject)
    }

    open override func supportedEvents() -> [String]!
    {
        return ["thirdLogin","finishPay","finishIap"]
    }

    @objc func getImgPath(_ path:(NSObject) -> ())
    {
        let path_document = NSHomeDirectory()
        //设置一个图片的存储路径
        let imagePath = path_document.appending("/Documents/pic.jpg")
//        let imagePath = "/Documents/pic.jpg"
        
        path([imagePath] as NSObject)
    }
    
    //内购结束，调用事件通知react
    func didFinishIap(status: Bool) {
        var ret:NSDictionary
        
        if(status)
        {
            ret = ["status": true]
        }
        else
        {
            ret = ["status": false]
        }
        
        self.bridge.eventDispatcher().sendAppEvent(withName: "finishIap", body:ret)
    }
    
    //支付结束，调用事件通知react
    func finishPay(status:Bool)
    {
        var ret:NSDictionary
        
        if(status)
        {
            ret = ["status": "true"]
        }
        else
        {
            ret = ["status": "false"]
        }
        
        self.bridge.eventDispatcher().sendAppEvent(withName: "finishPay", body:ret)
    }

    //发起支付
    @objc func confirmPay(_ payType:String, productType:Int, productId:String, userToken:String)
    {
        let data = [payType,String(productType),productId,userToken]
        
        homeView?.unionRise(data: data, callback: { (status, rise) in
            if(status)
            {
                let para = ["partnerid":rise.partnerid, "prepayid":rise.prepayid, "package":rise.package, "noncestr":rise.noncestr,
                            "timestamp":rise.timestamp, "sign":rise.sign]
                
                TPWechat.risePay(para: para as NSDictionary)
            }
        })
    }

    //Notify react to get user info
    //请求我们自己的服务器，获取用户信息
    func requestLoadUserData(_ type:String)
    {
        do
        {
            let dic = Locksmith.loadDataForUserAccount(userAccount: Key_User_Account)!
            let name = dic[Key_User_Name] as! String
            let id = dic[Key_User_Id] as! String
            let head = dic[Key_User_Head_Path] as! String
            
            let data = ["unionid":id, "nickname":name, "loginName":name, "headimgurl":head, "type":"wechat"]
            
            let opt = try HTTP.POST(SRef.Const(const: .outer_login_url), parameters: data)
            opt.start
            { response in
                if let err = response.error
                {
                    print("error: \(err.localizedDescription)")
                    return//also notify app of failure as needed
                }
                
                let data = response.data
                
                let dic = try! JSONSerialization.jsonObject(with: data,
                                                            options: JSONSerialization.ReadingOptions.mutableContainers) as! NSMutableDictionary
                
//                print("请求reAccess的response = \(data)")
                
                let entity = JSONDeserializer<MgcStatus>.deserializeFrom(dict: dic)
                let token = entity?.entity?.userToken
                let coin = entity?.entity?.coinIos
                
                if (token != nil)
                {
                    UserDefaults.standard.set(token, forKey: Key_User_Token)
                    UserDefaults.standard.set(coin, forKey: Key_User_Coin)
                    
                    let ret = ["login": "true"]
                    self.bridge.eventDispatcher().sendAppEvent(withName: "thirdLogin", body:ret)
                }
                else
                {
                    return
                }
            }
        }
        catch let error
        {
            print("got an error creating the request: \(error)")
        }
    }
}
